package com.zx.cloud.service;

import java.math.BigDecimal;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.text.NumberFormat;
import java.time.OffsetDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zx.cloud.Shift;
import com.zx.cloud.common.token.PasswordHashUtil;
import com.zx.cloud.controller.StatusCode;
import com.zx.cloud.domain.LoanOrder;
import com.zx.cloud.domain.SmsMsg;
import com.zx.cloud.domain.User;
import com.zx.cloud.persistence.ClientAuthMapper;
import com.zx.cloud.persistence.ClientMapper;
import com.zx.cloud.persistence.CrudMapper;
import com.zx.cloud.persistence.DictMapper;
import com.zx.cloud.persistence.ExtRoleMapper;
import com.zx.cloud.persistence.LoanOrderMapper;
import com.zx.cloud.persistence.RepayDetailMapper;
import com.zx.cloud.persistence.RepayOrderMapper;
import com.zx.cloud.persistence.SmsMsgMapper;
import com.zx.cloud.persistence.UserMapper;
import com.zx.cloud.util.Exceptions;
import com.zx.cloud.util.Page;
import com.zx.cloud.util.SmsCodeUtil;

/**
 * 用户表
 */
@Service
@Transactional
public class UserService extends CrudServiceImpl<User> {

	private static final Logger LOGGER = LoggerFactory.getLogger(UserService.class);

	@Autowired
	private ExtRoleMapper extRoleMapper;
	@Autowired
	private SmsMsgService smsMsgService;
	@Autowired
	private SmsMsgMapper smsMsgMapper;
	@Autowired
	private DictService dictService;
	@Autowired
	private UserMapper userMapper;
	@Autowired
	private LoanOrderMapper loanOrderMapper;
	@Autowired
	private RepayOrderMapper repayOrderMapper;
	@Autowired
	private ClientMapper clientMapper;
	@Autowired
	private  ClientAuthMapper   clientAuthMapper;
	@Autowired
	private RepayDetailMapper repayDetailMapper;
	@Autowired
	private DictMapper dictMapper;
	@Autowired
	private LogService logService;
	@Autowired
	public UserService(CrudMapper<User> mapper) {
		super(mapper);
	}

	@Override
	public int insert(User entity) {
		String username = entity.getUsername(); 
		if(null != userMapper.findUsername(username)){
				Shift.fatal(StatusCode.USER_EXISTS);
		}
		try {
			entity.setPassword(PasswordHashUtil.createHash("123456"));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
			throw Exceptions.unchecked(e);
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
			throw Exceptions.unchecked(e);
		}
		entity.setCreateDate(OffsetDateTime.now());//创建时间
		entity.setStatus(0);//初始状态
		super.insert(entity);
		
		Map<String, Object> rMap = new HashMap<String, Object>();
		rMap.put("roleId", entity.getRoleId());
		rMap.put("userId", entity.getId());
		extRoleMapper.insertUserRole(rMap);
		return 1;
	}

	@Override
	public int update(User entity) {
		super.update(entity);
		Map<String, Object> params =new HashMap<String, Object>();
		params.put("userId", entity.getId());
		Long roleId=extRoleMapper.findUserRole(params);
		if(null != roleId){
			extRoleMapper.removeUserId(entity.getId());
		}
		Map<String, Object> rMap = new HashMap<String, Object>();
		rMap.put("roleId", entity.getRoleId());
		rMap.put("userId", entity.getId());
		extRoleMapper.insertUserRole(rMap);
		return 1;
	}
	
	
	public int updatePSD(User user) {
		User insUser = userMapper.get(user.getId());
		
		int resultInt = 0; //操作结果状态 1：修改成功 2：旧密码输入错误
		
		try {
			if (!PasswordHashUtil.validatePassword(user.getOldPWD(), insUser.getPassword())) {
				resultInt = 2;
				return resultInt;
			} else {
				insUser.setPassword(PasswordHashUtil.createHash(user.getPassword()));
				super.update(insUser);
				resultInt = 1;
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (InvalidKeySpecException e) {
			e.printStackTrace();
		} 
		
		return resultInt;
	}
    /**
    * @Title: deleteUser  
    * @Description: 用户管理-删除用户
    * @return
    * @return int  
     */
	public int deleteUser(User entity) {
		entity.setStatus(1);
		super.update(entity);
		Map<String, Object> params =new HashMap<String, Object>();
		params.put("userId", entity.getId());
		Long roleId=extRoleMapper.findUserRole(params);
		if(null != roleId){
			extRoleMapper.removeUserId(entity.getId());
		}
		return 1;
	}
	   /**
	    * @Title: getUser  
	    * @Description: 用户管理-查看用户
	    * @return
	    * @return User  
	     */
		public 	User getUser(User entity) {
			User  user=super.get(entity.getId());
			Map<String, Object> params =new HashMap<String, Object>();
			params.put("userId", entity.getId());
			Long roleId=extRoleMapper.findUserRole(params);
			if (null != roleId) {
				user.setRoleId(user.getRoleId());
			}
			return user;
		}
		 /**
		    * @Title: updateUser  
		    * @Description: 用户管理-修改用户
		    * @return
		    * @return int  
		     */
		public int updateUser(User entity) {
			super.update(entity);
			Map<String, Object> params =new HashMap<String, Object>();
			params.put("userId", entity.getId());
			Long roleId=extRoleMapper.findUserRole(params);
			extRoleMapper.removeUserId(entity.getId());
			Map<String, Object> rMap = new HashMap<String, Object>();
			rMap.put("roleId", entity.getRoleId());
			rMap.put("userId", entity.getId());
			extRoleMapper.insertUserRole(rMap);
			return 1;
		}
		
		public int handleSmsCode(Long userId, String userPhone, String fromType){
			
			int returnInt = 0;
			
			if(null != clientMapper.findLoginNameExist(userPhone) && "1".equals(fromType)){
				Shift.fatal(StatusCode.USER_EXISTS, "用户已经存在, 请尝试登录");
			}
			
			// 设置Http请求参数
			Map<String, String> params = dictService.getSmsDataConfig(0);
			params.put("mobile", userPhone);
			
			int code = SmsCodeUtil.getCodeRandom();
			
			SmsMsg smsMsg = new SmsMsg();
			smsMsg.setUserId(userId);
			smsMsg.setPhone(userPhone);
			smsMsg.setCode(code+"");
			if(StringUtils.isNotEmpty(fromType)){
				smsMsg.setSmsType(Integer.parseInt(fromType));
			}
			OffsetDateTime nowDate = OffsetDateTime.now();
			smsMsg.setCreateDate(nowDate);
			OffsetDateTime overDate = OffsetDateTime.now();
			smsMsg.setOverDate(overDate);
			
			smsMsg.setRemark("记录用户获取验证码信息");
			
			String content = new String(code+"");
			params.put("content", content);
			params.put("templateId", "2008");
			
			returnInt = SmsCodeUtil.sendSmsCode(params);
			
			//保存短信验证码进表
			smsMsgService.insert(smsMsg);
			
			return returnInt;
		}
		
		public int verifySmsCode(Long userId, String userPhone, String userCode){
			
			int returnInt = 0;
			
			Map<String, Object> params =new HashMap<String, Object>();
			params.put("phone", userPhone);
			params.put("code", userCode);
			
			//根据手机号、验证码匹配数据库
			SmsMsg smsMsg = smsMsgMapper.findSmsCodeByPhone(params);
			
			if(null == smsMsg){
				Shift.fatal(StatusCode.SMS_CODE_ERROR, "验证码输入错误");
			}
			
			return returnInt;
		}
		
		 /**
         * 登录首页
         * @param user
         * @return user
         */
		public User loginFind(Long userId) {
			User result=userMapper.findUserRoleName(userId+"");
			return result;
		}
		/**
		 * 禁用用户
		 * @param entity
		 * @return
		 */
		public int banUser(User entity) {
			entity.setId(entity.getId());
			entity.setStatus(2);
			super.update(entity);
			
			return 1;
		}
		
		/**
		 * 启用用户
		 * @param entity
		 * @return
		 */
		public int startUser(User entity) {
			entity.setId(entity.getId());
			entity.setStatus(0);
			super.update(entity);
			
			return 1;
		}
		/**
		 * 根据账号查询用户
		 * @param user
		 * @return
		 */
		public Page<User> accountQuery(User user) {
			long count = userMapper.getAccountQueryList(user);
			Page<User> page = new Page<User>(user.getPageIndex_(), user.getPageSize_());
			page.setData(userMapper.findAccount(user));
			page.setTotalCount(count);
			return page;
		}
		/**
		 * @Description:首页展示关于订单信息
		 * @author likun
		 * @Create Time: 2017年11月8日上午9:38:26
		 * @return
		 */
		public Map<String, Object>  getHomeInfoToOrder(){
			Map<String, Object> resultMap=new HashMap<String, Object>();
			/**昨日数据*/
			//昨天注册人数
			long  yRegisterCount=clientMapper.getYesterdayClientCount();
			resultMap.put("yRegisterCount", yRegisterCount);
			//昨天身份认证数
			long yIdAuthCount=clientAuthMapper.getYesterdayIdAuthCount();
			resultMap.put("yIdAuthCount", yIdAuthCount);
			
			/**今日数据*/
			//当天注册人数
			Map<String, Object> params=new HashMap<String, Object>();
			long  tRegisterCount=clientMapper.getTodayClientCount(params);
			resultMap.put("tRegisterCount", tRegisterCount);
			//当天身份认证数
			long tIdAuthCount=clientAuthMapper.getTodayIdAuthCount();
			resultMap.put("tIdAuthCount", tIdAuthCount);
			
			//当天借款申请数量
			long tApplyCount=loanOrderMapper.getTodayLoanOrderCount(params);
			resultMap.put("tApplyCount", tApplyCount);
			//当天借款申请通过数量
			params.put("status",2);
			long tPassCount=loanOrderMapper.getTodayLoanOrderCountByPass(params);
			resultMap.put("tPassCount", tPassCount);
			//当天审核数量
			long tCheckCount=loanOrderMapper.getTodayLoanOrderCountByCheck(params);
			if(tPassCount >0 && tCheckCount >0 ){
				//当天借款通过率
				NumberFormat numberFormat = NumberFormat.getInstance();  
		        numberFormat.setMaximumFractionDigits(2);  
		        String nPassRate = numberFormat.format((float) tPassCount / (float) tCheckCount * 100);  
		        resultMap.put("tPassRate", nPassRate+"%");
			}else{
				 resultMap.put("tPassRate", "0");
			}
			//当天放款数量
			params.put("status",3);
			long tLoanCount=loanOrderMapper.getTodayLoanOrderCountByUpdate(params);
			resultMap.put("tLoanCount", tLoanCount);
			//当天还款数量
			long tRepayCount=repayDetailMapper.getTodayRepayCount(params);
			resultMap.put("tRepayCount", tRepayCount);
			/**累计数据*/
			//累计注册数
			long clientTotal=clientMapper.getClientTotal();
			resultMap.put("clientTotal", clientTotal);
			//累计身份认证数
			long idAuthTotal=clientAuthMapper.getIdAuthTotal();
			resultMap.put("idAuthTotal", idAuthTotal);
			
			//累计放款总金额
			BigDecimal  loanAmountTotal=loanOrderMapper.getLoanAmountTotal();
			resultMap.put("lAmountTotal", loanAmountTotal);
			//待还总金额
			BigDecimal  repayAmountTotal=repayOrderMapper.getRepayAmountTotal();
			resultMap.put("rAmountTotal", repayAmountTotal);
			//逾期还款总金额
			BigDecimal  overdueAmountTotal=repayOrderMapper.getOverdueAmountTotal();
			resultMap.put("oAmountTotal", overdueAmountTotal);
			/**待办事项*/
			//待审批订单数量
			LoanOrder  lOrder=new LoanOrder();
			lOrder.setStatus(0);
			long wCheckCount=loanOrderMapper.getAllLoanOrderCount(lOrder);
			resultMap.put("wCheckCount", wCheckCount);
			//待放款订单数量
			lOrder.setStatus(2);
			long wLoanCount=loanOrderMapper.getAllLoanOrderCount(lOrder);
			resultMap.put("wLoanCount", wLoanCount);
			return resultMap;
		}
		
		/**
		 * 重置密码
		 * @param entity
		 * @return
		 */
		public int resetPassword(User entity) {
			entity.setId(entity.getId());
			try {
				entity.setPassword(PasswordHashUtil.createHash("123456"));
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
				throw Exceptions.unchecked(e);
			} catch (InvalidKeySpecException e) {
				e.printStackTrace();
				throw Exceptions.unchecked(e);
			}
			
			super.update(entity);
			return 1;
		}
		
		/**
		 * 每次登录添加登录时间
		 * @param user
		 * @return
		 */
		public User updateLoginTime(User entity) {
			if(entity.getBeforeLoginDate() == null){
				entity.setBeforeLoginDate(entity.getLoginDate());
			}
			super.update(entity);
			return entity;
		}
		/**
		 * 獲取上一次登陸的ip地址
		 * @param user
		 */
		public void updateLoginIp(User user) {
			if(user.getBeforeLoginIp() == null){
				user.setBeforeLoginIp(user.getLoginIp());
			}
			super.update(user);
		}
}
